import "babel-polyfill"

const path = require('path')
const cookieParser = require('cookie-parser')

const express = require('express')
const app = express()

const history = require('connect-history-api-fallback')
app.use('/',history())

app.all('*', function (req, res, next) {
	res.header("Access-Control-Allow-Origin", "*")
	res.header("Access-Control-Allow-Headers", "X-Requested-With");
	// res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
	res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
	res.header("X-Powered-By", ' 3.2.1')
	res.header("Content-Type", "application/json;charset=utf-8")
	next()
})

//解析JSON
//文件大小限制
const bodyParser = require('body-parser');
// 解析 application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }))
// 解析 application/json
app.use(bodyParser.json({ limit: '50mb' }))

//请求头
const cors = require('cors')
app.use(cors());

//解析数据
// import { dataAnalysis } from './utils/middleware.js'
// app.use(dataAnalysis)

//托管静态路径
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public/dist')))


//token解析
import { decode } from 'js-base64'
app.use((req,res,next) => {
  const token = req.headers['sky-token']
  if(token){
    const { id,type } = JSON.parse(decode(token))
    if(!id || !type) return res.send({code:500,msg:'用户状态异常'})
    res.locals = { id,type }
  }
  next()
})


//路由
// app.use('/',  require('./routes/index'))
app.use('/node/user',  require('./routes/users'))
app.use('/node/file',require('./routes/file'))
app.use('/node/project',  require('./routes/project'))
app.use('/node/work',require('./routes/work'))
app.use('/node/placard',require('./routes/placard'))

//启动服务
const http = require('http')
const server = http.createServer(app)
import { pass_one_day } from './corn/index'
import { START_PORT } from './server.config'
server.listen(START_PORT,()=>{
  console.log(`运行成功: 127.0.0.1:${START_PORT}`)
	pass_one_day()//每天执行的任务
})